<template>
  <div class="global-message">
    <van-popup
      custom-style="{{customStyle}}"
      overlay-style="{{overlayStyle}}"
      show="{{ show }}" bind:close="onClose">
      <div class="global-message-success" v-if="type === 'success'">
        <image class="global-message-img" src="{{img.success}}"></image>
        <div class="global-message-text">提交成功!</div>
      </div>
      <div class="global-message-error" v-if="type === 'error'">
        <image class="global-message-img" src="{{img.error}}"></image>
        <div class="global-message-text">提交失败!</div>
        <div class="global-message-reason">{{reason}}</div>
      </div>
    </van-popup>
  </div>
</template>

<script>
  let img = {
    success: 'http://oss.kaoyanvip.cn/uploads/file1568872910753.png',
    error: 'http://oss.kaoyanvip.cn/uploads/file1568872883907.png',
  }

  export default {
    behaviors: [],
    data() {
      return {
        img,
        show: false,
        customStyle: 'width:300rpx; padding-top: 46rpx; padding-bottom: 28rpx; border-radius: 20rpx;',
        overlayStyle: 'background-color: rgba(21,21,21,.3);',
        type: 'success',
        reason: '',
        autoClose: true,
        time: 3000
      }
    },
    attached() {
      this.timeoutTask = null
    },
    pageLifetimes:{
      show() {
        if (this.timeoutTask) {
          clearTimeout(this.timeoutTask)
        }
      },
      hide() {
        this.doClose()
      }
    },
    methods: {
      show(type, data = {}) {
        let d = {
          type,
          show: true,
          ...data
        }

        if (!d.hasOwnProperty('autoClose')) {
          d.autoClose = true
        }

        if (!d.hasOwnProperty('time')) {
          d.time = 3000
        }

        this.setData(d);
        if (!d.autoClose) {
          return
        }

        if (d.autoClose || this.data.autoClose) {
          this.timeoutTask = setTimeout(() => {
            this.doClose()
          }, d.hasOwnProperty('time') ? d.time : this.data.time)
        }
      },
      doClose() {
        let d = { show: false }
        this.setData(d);
        clearTimeout(this.timeoutTask)
      },
      close() {
        this.doClose()
      },
      onClose() {
        this.doClose()
      },
    },
  }
</script>

<style lang="less">
  @import "../../app.component.less";

  .global-message {
    &-img {
      display: block;
      size: 87pt;
      margin: 0 auto 30pt;
    }
    &-text {
      #utils.ctext(30pt, #222222);
      text-align: center;
    }
    &-reason {
      padding-top: 20pt;
      #utils.ctext(24pt, #999999);
      text-align: center;
      max-width: 90%;
      margin: 0 auto;
    }
  }
</style>
